<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2019-09-04
 * Time: 15:16
 */

namespace extend\notify;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Sms
{
    protected $config = [];

    public function __construct()
    {
        $this->config = [
            'accessKeyId' => config('ali.accessKeyId'),
            'accessKeySecret' => config('ali.accessSecret'),
        ];
    }

    public function aLiDaYu($mobile, $templateCode, $template = [], $SignName = '')
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                //->scheme('https') //https | http（如果域名是https，这里记得开启）
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => $SignName ? $SignName : config('ali.smsSignName'),
                        'TemplateCode' => $templateCode,
                        'TemplateParam' => json_encode($template, JSON_UNESCAPED_UNICODE),
                    ],
                ])
                ->request();

            $response = $result->toArray();

            if ($response['Code'] == 'OK') {
                return true;
            } else {
                return $response['Message'];
            }
        } catch (ClientException $e) {
            return $e->getErrorMessage();
        } catch (ServerException $e) {
            return $e->getErrorMessage();
        }
    }

    public function addSmsTemplate($data)
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('AddSmsTemplate')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'TemplateType' => $data['type'],
                        'TemplateName' => $data['name'],
                        'TemplateContent' => $data['content'],
                        'Remark' => $data['remark'],
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

    public function deleteSmsTemplate($TemplateCode)
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('DeleteSmsTemplate')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'TemplateCode' => $TemplateCode,
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

    public function querySmsTemplate($TemplateCode)
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('QuerySmsTemplate')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'TemplateCode' => $TemplateCode,
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }


    /**
     * 审核失败编辑短信模板
     */
    public function modifySmsTemplate($data)
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('ModifySmsTemplate')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'TemplateType' => $data['type'],
                        'TemplateName' => $data['name'],
                        'TemplateCode' => $data['code'],
                        'TemplateContent' => $data['content'],
                        'Remark' => $data['remark'],
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

    /*
     * 群发消息
     */
    public function SendBatchSms($mobileJson, $templateCode, $template = [])
    {
        $config = $this->config;
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])->regionId('cn-hangzhou')->asDefaultClient();
        $rootPath = \think\facade\Env::get('root_path');
        if ($rootPath != '/home/wwwroot/cjx.chudachu.com/') {
            return ['Code' => 'OK'];
        }

        $SignNameJson = [];
        $template = [];
        foreach ($mobileJson as $key => $value) {
            $SignNameJson[$key] = config('ali.smsName');
            $template[$key]['name'] = 'TemplateParamJson';
        }
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendBatchSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumberJson' => json_encode($mobileJson),
                        'SignNameJson' => json_encode($SignNameJson, JSON_UNESCAPED_UNICODE),
                        'TemplateCode' => $templateCode,
                        'TemplateParamJson' => json_encode($template, JSON_UNESCAPED_UNICODE),
                    ],
                ])
                ->request();
            $response = $result->toArray();
            if ($response['Code'] == 'OK') {
                return true;
            } else {
                return $response['Message'];
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}